package com.microservice.wechat.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.microservice.api.common.PageResult;
import com.microservice.api.common.Result;
import com.microservice.api.wechat.ArticleServiceClient;
import com.microservice.api.wechat.dto.ArticleDTO;
import com.microservice.api.wechat.dto.UserStatisticsDTO;
import com.microservice.common.utils.WechatTokenUtil;
import com.microservice.wechat.entity.Article;
import com.microservice.api.wechat.dto.UserBindConfigDTO;
import com.microservice.wechat.service.ArticleService;
import com.microservice.wechat.service.WechatDraftService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文章服务API实现
 * 实现common-api中定义的ArticleServiceApi接口
 * 
 * @author wechat-service
 */
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController implements ArticleServiceClient {

    @Autowired

   WechatDraftService  wechatDraftService;
    @Autowired
    ArticleService articleService;

    @Autowired
    private WechatTokenUtil wechatTokenUtil;

    @Autowired
    private com.microservice.wechat.service.ArticleReviewRecordService articleReviewRecordService;

    @Override
    public Result<ArticleDTO> save(ArticleDTO articleDTO) {
        try {
            Article article = new Article();
            BeanUtils.copyProperties(articleDTO, article);

            article.setCreateTime(new Date());
            if (article.getStatus() == null) {
                article.setStatus(0); // 默认未审核
            }
            List<UserBindConfigDTO> list= articleService.getUserBindAppId(Long.parseLong(articleDTO.getUserId()));
            //如果账号跟公众号绑定 则选择绑定的公众号进行发布 （目前是一个人最好绑定一个公众号）
            if(articleDTO.getAppId() ==null && !list.isEmpty()){
                //随机选择公众号进行文章塞入 后续算法逻辑仍需要优化
                article.setAppId(list.stream().findFirst().get().getAppId());

            }
            if(articleDTO.getAppId() ==null && list.isEmpty()){
                Map<String,String> tokenMap= wechatTokenUtil.getRandomAccessToken();
                article.setAppId(tokenMap.get("appId"));
            }

            log.info("保存文章："+article.toString());
           // article.setMediaId(wechatTokenUtil.getCoverId(tokenMap.get("appId")));已经在主表设置了
            boolean success = articleService.save(article);
            if (success) {
                BeanUtils.copyProperties(article, articleDTO);
                return Result.success(articleDTO);
            } else {
                return Result.error("新增文章失败");
            }
        } catch (Exception e) {
            return Result.error("新增文章失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> delete(Long id) {
        try {
            boolean success = articleService.removeById(id);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    @Override
    public Result<ArticleDTO> update(ArticleDTO articleDTO) {
        try {
            if (articleDTO.getId() == null) {
                return Result.error("文章ID不能为空");
            }

            Article article = new Article();
            BeanUtils.copyProperties(articleDTO, article);

            boolean success = articleService.updateById(article);
            if (success) {
                return Result.success(articleDTO);
            } else {
                return Result.error("更新文章失败");
            }
        } catch (Exception e) {
            return Result.error("更新文章失败: " + e.getMessage());
        }
    }

    @Override
    public Result<ArticleDTO> getById(Long id) {
        try {
            Article article = articleService.getById(id);
            if (article != null) {
                ArticleDTO articleDTO = new ArticleDTO();
                BeanUtils.copyProperties(article, articleDTO);
                return Result.success(articleDTO);
            } else {
                return Result.error("文章不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<UserBindConfigDTO>> getUserBindAccount(Long id) {
        List<UserBindConfigDTO> userBindAppId=articleService.getUserBindAppId(id);
        return Result.success(userBindAppId);
    }

    @Override
    public Result<PageResult<ArticleDTO>> page(int current, int size, Integer status, String userId) {
        try {
            Page<Article> page = articleService.page(current, size, status, userId);

            List<ArticleDTO> dtoList = page.getRecords().stream()
                    .map(article -> {
                        ArticleDTO dto = new ArticleDTO();
                        BeanUtils.copyProperties(article, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());

            PageResult<ArticleDTO> pageResult = new PageResult<>();
            pageResult.setRecords(dtoList);
            pageResult.setTotal(page.getTotal());
            pageResult.setCurrent(page.getCurrent());
            pageResult.setSize(page.getSize());
            pageResult.setPages(page.getPages());

            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error("分页查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<PageResult<ArticleDTO>> listByUserId(String userId,Integer status, int current, int size) {
        try {
            Page<Article> page = articleService.listByUserId(userId,status, current, size);

            List<ArticleDTO> dtoList = page.getRecords().stream()
                    .map(article -> {
                        ArticleDTO dto = new ArticleDTO();
                        BeanUtils.copyProperties(article, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());

            PageResult<ArticleDTO> pageResult = new PageResult<>();
            pageResult.setRecords(dtoList);
            pageResult.setTotal(page.getTotal());
            pageResult.setCurrent(page.getCurrent());
            pageResult.setSize(page.getSize());
            pageResult.setPages(page.getPages());

            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error("查询用户文章失败: " + e.getMessage());
        }
    }

    @Override
    public Result<PageResult<ArticleDTO>> listByStatus(Integer status, int current, int size) {
        try {
            Page<Article> page = articleService.listByStatus(status, current, size);

            List<ArticleDTO> dtoList = page.getRecords().stream()
                    .map(article -> {
                        ArticleDTO dto = new ArticleDTO();
                        BeanUtils.copyProperties(article, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());

            PageResult<ArticleDTO> pageResult = new PageResult<>();
            pageResult.setRecords(dtoList);
            pageResult.setTotal(page.getTotal());
            pageResult.setCurrent(page.getCurrent());
            pageResult.setSize(page.getSize());
            pageResult.setPages(page.getPages());

            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error("查询文章失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> deleteBatch(Long[] ids) {
        try {
            int count = 0;
            for (Long id : ids) {
                if (articleService.removeById(id)) {
                    count++;
                }
            }
            return Result.success("成功删除 " + count + " 条记录");
        } catch (Exception e) {
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> updateStatus(Long id, Integer status) {
        try {
            Article article = new Article();
            article.setId(id);
            article.setStatus(status);

            boolean success = articleService.updateById(article);
            return success ? Result.success("状态更新成功") : Result.error("状态更新失败");
        } catch (Exception e) {
            return Result.error("状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统计信息
     * 统计已通过审核的文章数量和所有文章的总浏览量
     *
     * @param userId 用户ID
     * @return 用户统计信息
     */
    @GetMapping("/statistics/{userId}")
    public Result<UserStatisticsDTO> getUserStatistics(@PathVariable("userId") Long userId) {
        try {
            UserStatisticsDTO statistics = articleService.getUserStatistics(userId);
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取用户统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 审核文章（支持通过和拒绝，拒绝时记录原因）
     *
     * @param id 文章ID
     * @param status 审核状态：1-通过，2-拒绝
     * @param rejectReason 拒绝原因（状态为2时必填）
     * @param reviewerId 审核人员ID
     * @param reviewerName 审核人员姓名
     * @return 审核结果
     */
    @Override
    public Result<String> reviewArticle(
            @PathVariable("id") Long id,
            @RequestParam("status") Integer status,
            @RequestParam(value = "rejectReason", required = false) String rejectReason,
            @RequestParam("reviewerId") Long reviewerId,
            @RequestParam("reviewerName") String reviewerName) {
        try {
            // 参数校验
            if (status != 2 && status != 3) {
                return Result.error("审核状态只能是2(通过)或3(拒绝)");
            }
            if (status == 3 && (rejectReason == null || rejectReason.trim().isEmpty())) {
                return Result.error("拒绝文章时必须填写拒绝原因");
            }

            // 查询文章
            Article article = articleService.getById(id);
            if (article == null) {
                return Result.error("文章不存在");
            }

            // 更新文章状态
            article.setStatus(status);
            boolean updated = articleService.updateById(article);
            if (!updated) {
                return Result.error("更新文章状态失败");
            }

            // 保存审核记录
            com.microservice.wechat.entity.ArticleReviewRecord record = new com.microservice.wechat.entity.ArticleReviewRecord();
            record.setArticleId(id);
            record.setArticleTitle(article.getTitle());
            record.setReviewStatus(status);
            record.setRejectReason(rejectReason);
            record.setReviewerId(reviewerId);
            record.setReviewerName(reviewerName);
            record.setReviewTime(java.time.LocalDateTime.now());
            articleReviewRecordService.save(record);

            if(status.equals(2)){
                //发送到微信服务器
                Result<com.microservice.api.wechat.dto.DraftAddResponse> draftAddResponseResult=  wechatDraftService.addDraft(article);
                log.info("上传草稿结果："+draftAddResponseResult.getMessage());
            }
            String result = status == 2 ? "文章审核通过" : "文章已拒绝";
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("审核失败: " + e.getMessage());
        }
    }

    /**
     * 查询文章的审核记录列表
     *
     * @param articleId 文章ID
     * @return 审核记录列表
     */
    @Override
    public Result<List<com.microservice.api.wechat.dto.ArticleReviewRecordDTO>> getReviewRecords(@PathVariable("articleId") Long articleId) {
        try {
            List<com.microservice.wechat.entity.ArticleReviewRecord> records = articleReviewRecordService.getByArticleId(articleId);
            List<com.microservice.api.wechat.dto.ArticleReviewRecordDTO> dtoList = records.stream()
                    .map(record -> {
                        com.microservice.api.wechat.dto.ArticleReviewRecordDTO dto = new com.microservice.api.wechat.dto.ArticleReviewRecordDTO();
                        BeanUtils.copyProperties(record, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            return Result.success(dtoList);
        } catch (Exception e) {
            return Result.error("查询审核记录失败: " + e.getMessage());
        }
    }

    /**
     * 查询文章的最新审核记录
     *
     * @param articleId 文章ID
     * @return 最新审核记录
     */
    @Override
    public Result<com.microservice.api.wechat.dto.ArticleReviewRecordDTO> getLatestReviewRecord(@PathVariable("articleId") Long articleId) {
        try {
            com.microservice.wechat.entity.ArticleReviewRecord record = articleReviewRecordService.getLatestByArticleId(articleId);
            if (record != null) {
                com.microservice.api.wechat.dto.ArticleReviewRecordDTO dto = new com.microservice.api.wechat.dto.ArticleReviewRecordDTO();
                BeanUtils.copyProperties(record, dto);
                return Result.success(dto);
            }
            return Result.success(null);
        } catch (Exception e) {
            return Result.error("查询最新审核记录失败: " + e.getMessage());
        }
    }
}
